﻿using Grpc.Net.Client.Balancer;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Nacos.AspNetCore.V2;
using Nacos.V2;
using Nacos.V2.Common;
using Nacos.V2.Naming.Dtos;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Nacos.Provider.gRPC
{
    public class NacosResolver : PollingResolver
    {
        private readonly IEnumerable<Instance> instances = null;
        private readonly NacosGrpcChannelOptions grpcChannelOptions = null;

        public NacosResolver(ILoggerFactory loggerFactory, IEnumerable<Instance> instances, NacosGrpcChannelOptions nacosGrpcChannelOptions)
            : base(loggerFactory)
        {
            this.instances = instances;
            this.grpcChannelOptions = nacosGrpcChannelOptions;
        }

        protected override Task ResolveAsync(CancellationToken cancellationToken)
        {
            return Task.Run(() =>
             {
                 var services = new List<BalancerAddress>();
                 if (instances != null && instances.Any())
                     services.AddRange(instances.Select(i => new BalancerAddress(i.Ip, (int)(grpcChannelOptions.PortProcess?.Invoke(i.Port)))));
                 Listener(ResolverResult.ForResult(services));
             });
        }
    }
}
